﻿Imports System.Windows
Imports System.Windows.Documents

' Derive from AdornerDecorator in case the 
' Window that hosts the GraphView has a custom
' template that does not include an AdornerLayer.

''' <summary>
''' Hosts a NodeConnectionAdorner in the adorner layer.
''' </summary>
Public Class NodeConnectionAdornerDecorator
    Inherits AdornerDecorator

#Region "Constructor"

    Public Sub New()
        AddHandler MyBase.Loaded, AddressOf Me.OnLoaded
    End Sub

#End Region

#Region "OnLoaded"

    Sub OnLoaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
        Dim layer As AdornerLayer = MyBase.AdornerLayer
        If layer Is Nothing Then
            Return
        End If

        _adorner = New NodeConnectionAdorner(Me)
        layer.Add(_adorner)
        Me.GiveGraphToAdorner()
    End Sub

#End Region

#Region "Graph (DP)"

    Public Property Graph() As Graph
        Get
            Return DirectCast(GetValue(GraphProperty), Graph)
        End Get
        Set(ByVal value As Graph)
            SetValue(GraphProperty, value)
        End Set
    End Property

    Public Shared ReadOnly GraphProperty As DependencyProperty =
        DependencyProperty.Register("Graph",
                                    GetType(Graph),
                                    GetType(NodeConnectionAdornerDecorator),
                                    New UIPropertyMetadata(Nothing, AddressOf OnGraphChanged))

    Shared Sub OnGraphChanged(ByVal sender As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
        TryCast(sender, NodeConnectionAdornerDecorator).GiveGraphToAdorner()
    End Sub

#End Region

#Region "Private Helpers"

    Sub GiveGraphToAdorner()
        If (_adorner IsNot Nothing) And (Me.Graph IsNot Nothing) Then
            _adorner.Graph = Me.Graph
        End If
    End Sub

#End Region

#Region "Fields"

    Private _adorner As NodeConnectionAdorner

#End Region

End Class
